package com.example.springboot.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.springboot.common.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.entity.Sign;
import com.example.springboot.entity.User;
import com.example.springboot.service.ISignService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import com.example.springboot.service.IExamService;
import com.example.springboot.entity.Exam;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgc
 * @since 2023-10-04
 */
@RestController
@RequestMapping("/exam")
public class ExamController {

    @Resource
    private IExamService examService;

    @Resource
    private ISignService signService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody Exam exam) {  //@RequestBody接收前端数据

        examService.saveOrUpdate(exam);
        return Result.success();
    }

    //查询所有数据
    @GetMapping()
    public Result findAll() {
        return Result.success(examService.list());
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(examService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(examService.removeByIds(ids));
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(examService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {

        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        Page<Exam> page = examService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for (Exam exam : page.getRecords()) {
            // 设置考试状态
            setSate(exam);
            examService.updateById(exam);
        }
        return Result.success(page);
    }

    @GetMapping("/page/front")
    public Result findPageFront(@RequestParam String name,
                                @RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {

        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        Page<Exam> page = examService.page(new Page<>(pageNum, pageSize), queryWrapper);
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser.getRole().equals("ROLE_USER")) {
            queryWrapper.eq("user", currentUser.getUsername());
        }
        // 查出当前用户所有报名的考试
        List<Sign> signList = signService.list(new QueryWrapper<Sign>().eq("user_id", currentUser.getId()));
        for (Exam exam : page.getRecords()) {
            // 其他情况都是false,不能考试的
            exam.setEnable(false);
            Integer examId = exam.getId();
            // 当前用户的报名列表里有这个考试，而且是审核通过的，我们才能设置 开始考试的按钮状态
            signList.stream().filter(sign -> sign.getExamId().equals(examId)).findFirst().ifPresent(sign -> {
                exam.setEnable("审核通过".equals(sign.getState()));
            });
            //设置考试状态
            setSate(exam);
            examService.updateById(exam);
        }
        return Result.success(page);
    }

    private void setSate(Exam exam) {
        String time = exam.getTime();
        DateTime dateTime = DateUtil.parse(time, "yyyy-MM-dd HH:mm");
        Date now = new Date();
       //考试的开始时间在当前时间之后，并且开始的结束时间在当前的时间之前，考试默认2小时
        if (DateUtil.compare(dateTime, now) <= 0 && DateUtil.compare(DateUtil.offsetMinute(dateTime, exam.getDuration()), now) > 0) {
            exam.setState("进行中");
//                如果考试时间在当前时间前之后，未开始
        } else if (DateUtil.compare(dateTime, now) > 0) {
            exam.setState("未开始");
        } else {
            exam.setState("已结束");
        }
    }
}



